import React, { Component } from 'react';
import { Col, Icon, Popover, Row, Table, Tabs, Tag, Timeline } from 'antd';
import { getApprovelHistory, messages } from 'share/common';
import Condition from 'components/condition';
import FileUpload from 'components/file-upload';
import errorMessage from "share/errorMessage";
import IeFileUpload from 'components/template/ie-file-upload/ie-file-upload';
import expenseService from 'containers/my-account/expense.service'
import moment from 'moment'

const { TabPane } = Tabs;
const { If, Else } = Condition;
import dataSources from 'containers/my-account/data-sources/data-sources';
const { showUserInfo, cardsignTypeInfo } = dataSources;

class InvoiceDetail extends Component {
  constructor(props) {
    super(props);
    this.state = {
      columns: [
        {
          title: messages('my-account.key27'/*货物或应税劳务、服务名称*/),
          dataIndex: 'goodsName',
          render: goodsName => goodsName || '-'
        },
        {
          title: messages('my-account.key28'/*规格型号*/),
          dataIndex: 'vehicleType',
          render: vehicleType => vehicleType || '-'
        },
        {
          title: messages('common.unit')/*单位*/, dataIndex: 'unit'
        },
        {
          title: messages('common.number')/*数量*/, dataIndex: 'count'
        },
        {
          title: messages('common.price')/*单价*/,
          dataIndex: 'unitPrice',
          render: (unitPrice, item) => (Number(unitPrice) / 100).toFixed(props.getCurrencyPrecision(item))
        },
        {
          title: messages('common.amount')/*金额*/,
          dataIndex: 'amount',
          render: (amount, item) => (amount !== undefined && amount !== null) ? (Number(amount) / 100).toFixed(props.getCurrencyPrecision(item)) : '-'
        },
        {
          title: messages('my-account.key29'/*税率*/),
          dataIndex: 'taxRateString',
          render: value => (value !== undefined && value !== null) ? (isNaN(value) ? value : `${value}%`) : 0
        },
        {
          title: messages('common.tax')/*税额*/,
          dataIndex: 'taxPrice',
          render: (taxPrice, item) => (taxPrice !== undefined && taxPrice !== null) ?
            (isNaN(taxPrice) ? taxPrice : (Number(taxPrice) / 100).toFixed(props.getCurrencyPrecision(item))) : 0
        }
      ],
      travelColumns: [
        {
          title: messages('my-account.key30'/*项目名称*/),
          dataIndex: 'goodsName',
          width: '23%',
          render: goodsName => goodsName || '-'
        },
        {
          title: messages('my-account.key31'/*车牌号*/),
          dataIndex: 'plateNumber',
          width: '13%',
          render: plateNumber => plateNumber || '-'
        },
        {
          title: messages('my-account.key32'/*类型*/),
          dataIndex: 'carType',
          width: '8%',
          render: carType => carType || '-'
        },
        {
          title: messages('my-account.key33'/*通行日期起*/),
          dataIndex: 'passDateFrom',
          width: '17%',
          render: passDateFrom => passDateFrom || '-'
        },
        {
          title: messages('my-account.key34'/*通行日期至*/),
          dataIndex: 'passDateTo',
          width: '17%',
          render: passDateTo => passDateTo || '-'
        },
        {
          title: messages('common.amount')/*金额*/,
          dataIndex: 'amount',
          width: '8%',
          render: (amount, item) => (amount !== undefined && amount !== null) ? (Number(amount) / 100).toFixed(props.getCurrencyPrecision(item)) : '-'
        },
        {
          title: messages('my-account.key29'/*税率*/),
          dataIndex: 'taxRateString',
          width: '8%',
          render: value => (value !== undefined && value !== null) ? (isNaN(value) ? value : `${value}%`) : '-'
        },
        {
          title: messages('common.tax')/*税额*/,
          dataIndex: 'taxPrice',
          width: '8%',
          render: (taxPrice, item) => (taxPrice !== undefined && taxPrice !== null) ?
            (isNaN(taxPrice) ? taxPrice : (Number(taxPrice) / 100).toFixed(props.getCurrencyPrecision(item))) : '-'
        }
      ],
      changeRecord:[],
    };
  }

  componentWillMount() {
    let { changeRecord } = this.state;
    const { invoice: { id = null, checkResult = null, pdfDamaged = false } } = this.props;
    if (this.handleIsShowTag()) {
      expenseService.getInvoiceChangeRecordV2({id, checkResult, pdfDamaged})
        .then(res => {
          changeRecord = res.data;
          changeRecord.map((tag, index) => {
            if (tag.type === 'MODIFY_RECEIPT') {
              tag.history.map(item => {
                item.id = index + 1;
                index === 0 ? item.icon = 'up-circle-o' : item.icon = 'down-circle-o';
                index === 0 ? item.color = '#4CA8BC' : item.color = '#EBA945';
                return item;
              });
            }
            tag.description && (tag.description = tag.description.split('\n'));
            return tag;
          });
          this.setState({ changeRecord });
        })
        .catch(err => {
          errorMessage(err.response);
        });
    }
  }

  handleIsShowTag = () => { // 是否显示标签说明
    const { invoice } = this.props;
    return invoice.receiptLabels.some(item => {
      if (['MODIFY_RECEIPT', 'INSP_FAILED', 'MISMATCHED_INV'].indexOf(item.type || item.code) !== -1  || invoice['pdfDamaged'] === true) {
        return true;
      }
    });
  };

  renderDetail = (title, value, span = 12, calibration = false, titleSpan = 8) => {
    return (
      <Col span={span} className="invoice-row">
        <Row>
          <Col span={titleSpan} className="invoice-title">
            <Popover content={title}>{title}：</Popover>
          </Col>
          <Col span={24 - titleSpan} className={`invoice-detail ${calibration && 'text-decoration'}`}>
            {value ? <Popover content={value}>{value}</Popover> : '-'}
          </Col>
        </Row>
      </Col>
    );
  };

  renderTollType = (title, value) => {
    let result = '-';
    //tollType 06:存在 07: 不存在
    if (value) {
      result = value === '06' ? messages('my-account.key299')/*存在*/ : messages('my-account.key300')/*不存在*/
    }
    return (
      <Col span={12} className="invoice-row">
        <Row>
          <Col span={8} className="invoice-title">{title}:</Col>
          <Col span={16} className="invoice-detail">{result}</Col>
        </Row>
      </Col>
    );
  };

  //抬头建议信息显示
  promptMessage = (title, invoice, type, span = 12) => {
    const titleSpan = 8;
    //抬头有误建议的建议信息
    const suggestedKeys = {
      title: 'suggestedTitle', //抬头
      draweeNo: 'suggestedDraweeNo', //税号
      draweeAddressPhone: 'suggestedDraweeAddressPhone', //地址电话
      draweeBankAccount: 'suggestedDraweeBankAccount' //开户行及账号
    };
    return (
      <div>
        {this.renderDetail(title, invoice[type], span, invoice[suggestedKeys[type]])}
        <If value={invoice[suggestedKeys[type]]}>
          <Row>
            <Col span={titleSpan} className="invoice-title"/>
            <Col span={24 - titleSpan} className="invoice-detail">{invoice[suggestedKeys[type]]}</Col>
          </Row>
        </If>
      </div>
    );
  };

  //表格数据为空时的显示文案
  getEmptyText = () => {
    const { invoice } = this.props;
    //区块链发票
    if (invoice.blockchain) {
      return messages('my-account.key301')/*区块链发票：国税局不支持查验，无法获取发票行信息*/;
    }
    return messages('my-account.key302')/*暂无数据*/;
  };

  renderTabContent = () => {
      const { invoice, canExpense, handleShowBrief, getCurrencyPrecision, getInvoiceFreePrint, handlePrint,
        isPreViewCallBack, handlePreViewCallBack } = this.props;
      const { columns, travelColumns } = this.state;
      let hasInvoiceImage = false;
      (invoice.slicingAttachment && invoice.slicingAttachment.fileURL) && (hasInvoiceImage = true);
      (invoice.originAttachment && invoice.originAttachment.fileURL) && (hasInvoiceImage = true);
      const moreInfo = JSON.parse(invoice.moreInfo || '{}');
      const moreInfoLabel = JSON.parse(invoice.moreInfoLabel || '{}');
      const electronicFlag = invoice.cardsignType === 'APPCARDSIGN' || invoice.cardsignType === 'JSCARDSIGN';
      const alipayFlag = invoice.cardsignType === 'ALICARDSIGN';
      return (
        <section>
          <div className="invoice-detail-area">
            <Row>
              <Col span={hasInvoiceImage ? 21 : 24}>
                <Row>
                  {
                    invoice.billingTime &&
                    this.renderDetail(messages('my-account.key3'/*开票日期*/),
                      (invoice.billingTime ? new Date(invoice.billingTime * 1000) : new Date()).format('yyyy-MM-dd'),
                      12, false, hasInvoiceImage ? 9 : 8)
                  }
                  {this.renderDetail(messages('my-account.key4'/*发票代码*/), invoice.billingCode, 12, false, hasInvoiceImage ? 9 : 8)}
                  {this.renderDetail(messages('my-account.key6'/*发票号码*/), invoice.billingNo, 12, false, hasInvoiceImage ? 9 : 8)}
                  {this.renderDetail(messages('my-account.key53'/*机器编号*/), invoice.deviceNumber, 12, false, hasInvoiceImage ? 9 : 8)}
                  {this.renderDetail(messages('my-account.key8'/*校验码*/), invoice.checkCode, 12, false, hasInvoiceImage ? 9 : 8)}
                  {this.renderDetail(messages('my-account.key246')/*归属人*/, invoice.receiptOwner, 12, false, hasInvoiceImage ? 9 : 8)}
                  {this.renderDetail(messages('my-account.key303')/*人员信息*/, showUserInfo[invoice.showUserInfo] || '-', 12, false, hasInvoiceImage ? 9 : 8)}
                </Row>
              </Col>
              {hasInvoiceImage && (
                <Col span={3}>
                  <Condition>
                    <If value={window.ISIE9}>
                      <IeFileUpload defaultFileList={[invoice.slicingAttachment || invoice.originAttachment]} disabled/>
                    </If>
                    <Else>
                      <FileUpload
                        defaultFileList={[invoice.slicingAttachment || invoice.originAttachment]}
                        isPreViewCallBack={isPreViewCallBack}
                        handlePreViewCallBack={handlePreViewCallBack}
                        attachmentType="INVOICE_IMAGES"
                        showFileName={false}
                        disabled
                      />
                    </Else>
                  </Condition>
                </Col>
              )}
            </Row>
            <Row className="invoice-row">
              <Col span={4} className="invoice-title">{messages('my-account.key50'/*价税合计*/)}:</Col>
              <Col span={20} className="invoice-detail">
                <b className="invoice-currency">{invoice.vatInvoiceCurrencyCode}</b>
                <b className="invoice-amount">{(invoice.fee / 100).toFixed(getCurrencyPrecision(invoice))}</b>
                ({messages('my-account.key48'/*金额合计*/)}({messages('my-account.key180')/*不含税*/})：
                {typeof invoice.feeWithoutTax === 'number' ? (invoice.feeWithoutTax / 100).toFixed(getCurrencyPrecision(invoice)) : '-'}
                &nbsp;{messages('my-account.key49'/*税额合计*/)}：
                {(invoice.taxString === null || invoice.taxString === "") ? '-' : (
                  !isNaN(invoice.taxString) ? (Number(invoice.taxString) / 100).toFixed(getCurrencyPrecision(invoice)) : invoice.taxString
                )})
              </Col>
            </Row>
            <If value={invoice.nonDeductibleAmount}>
              <Col span={4}
                   className="invoice-title">{messages('common.total.amount')/*总金额*/}:</Col>
              <Col span={20} className="invoice-detail">
                <b className="invoice-currency">{invoice.vatInvoiceCurrencyCode}</b>
                <b className="invoice-amount">{((invoice.fee + invoice.nonDeductibleAmount) / 100).toFixed(getCurrencyPrecision(invoice))}</b>
                ({messages('my-account.key50'/*价税合计*/)}：{(invoice.fee / 100).toFixed(getCurrencyPrecision(invoice))}
                {messages('my-account.key236')/*不可抵扣*/}：{((invoice.nonDeductibleAmount) / 100).toFixed(getCurrencyPrecision(invoice))})
              </Col>
            </If>
            {
              invoice.invoiceTypeNo === '14' && (
                <div>
                  <Row>
                    {this.renderTollType(messages('my-account.key54'/*通行费标志*/), invoice.tollType)}
                  </Row>
                </div>
              )
            }
            <Row className="invoice-row">
              <Col span={4} className="invoice-title">{messages('common.remark')/*备注*/}:</Col>
              <Col span={20} className="invoice-detail">{invoice.remark || '-'}</Col>
            </Row>

            <Row className="invoice-row">
              <Col span={4} className="invoice-title">{messages('my-account.key292')/*发票来源*/}:</Col>
              <Col span={20} className="invoice-detail">{cardsignTypeInfo[invoice.cardsignType] || '-'}</Col>
            </Row>
            <Table
              size="small"
              style={{ margin: '10px 0' }}
              columns={invoice.invoiceTypeNo !== '14' ? columns : travelColumns}
              dataSource={invoice.invoiceGoods}
              rowKey={(record, index) => index}
              pagination={false}
              locale={{ emptyText: this.getEmptyText() }}
            />
            <Row>
              {this.promptMessage(messages('my-account.key52'/*购买方*/), invoice, 'title', 24)}
              {this.promptMessage(messages('my-account.key56'/*纳税人识别号*/), invoice, 'draweeNo', 24)}
              {this.promptMessage(messages('my-account.key57'/*地址/电话*/), invoice, 'draweeAddressPhone', 24)}
              {this.promptMessage(messages('my-account.key58'/*开户行/账户*/), invoice, 'draweeBankAccount', 24)}
            </Row>
            <hr/>
            <Row>
              {this.renderDetail(messages('my-account.key51'/*销售方*/), invoice.payee, 24)}
              {this.renderDetail(messages('my-account.key56'/*纳税人识别号*/), invoice.payeeNo, 24)}
              {this.renderDetail(messages('my-account.key57'/*地址/电话*/), invoice.payeeAddressPhone, 24)}
              {this.renderDetail(messages('my-account.key58'/*开户行/账户*/), invoice.payeeBankAccount, 24)}
            </Row>
            <If value={Object.keys(moreInfo).length > 0}>
              <hr/>
            </If>
            <Row>
              {
                Object.keys(moreInfo)
                  .map(key => (this.renderDetail(moreInfoLabel[key], moreInfo[key], 24)))
              }
            </Row>
          </div>
          <div className="invoice-operate">
            {canExpense &&
            <a onClick={() => handleShowBrief(false)}>{messages('my-account.key59'/*收起详情*/)}</a>}
            {!getInvoiceFreePrint(invoice) && (electronicFlag || alipayFlag) && invoice.pdfUrl && !invoice.pdfDamaged &&
            <a onClick={(e) => handlePrint(e, invoice)}>{messages('common.print')/*打印*/}</a>}
          </div>
        </section>
      );
  };

  renderTags = () => {
    const { changeRecord } = this.state;
    return (
      changeRecord.map(tag =>
        <section className="invoice-desc">
          <h3 className="invoice-desc-title">{tag.name}</h3>
          <If value={tag.type === 'MODIFY_RECEIPT'}>
            {
              (tag.history || []).map(record => {
                return (
                  <Timeline className="invoice-change">
                    <Timeline.Item
                      key={record.id}
                      dot={<Icon type={record.icon} style={{ color: record.color }}/>}>
                      <Row>
                        <Col span={6}>{moment(record.createdDate)
                          .format('YYYY-MM-DD HH:mm')}</Col>
                        <Col span={14} className="invoice-change-content">
                          <div>{record['operatorType']} {record['detailInfo'].map(item => `"${item.property}"`)
                            .join('、')}</div>
                          {
                            record['detailInfo'].map(item => {
                              return (
                                <div className="invoice-change-detail">
                                  {messages('my-account.key293', {
                                    arg1: item.property,
                                    arg2: item.oldValue || messages('setting.key1832'),
                                    arg3: item.newValue || messages('setting.key1832')
                                  })/*{arg1}：从 {arg2} 改为 {arg3}*/}
                                </div>
                              );
                            })
                          }
                        </Col>
                        <Col span={4} className="invoice-change-author">
                          {record.operatorName}
                        </Col>
                      </Row>
                    </Timeline.Item>
                  </Timeline>
                );
              })}
          </If>
          {
            tag.description && tag.description.map(desc => <p className="invoice-desc-detail">{desc}</p>)
          }
        </section>
      )
    );
  };

  render() {
    return (
      this.handleIsShowTag()
        ? (
          <Tabs defaultActiveKey="1">
            <TabPane tab={messages('my-account.key294')/*发票信息*/} key="1">
              {this.renderTabContent()}
            </TabPane>
            <TabPane tab={messages('my-account.key304')/*标签说明*/} key="2">
              {this.renderTags()}
            </TabPane>
          </Tabs>
          )
        : this.renderTabContent()
    );
  }
}

InvoiceDetail.propTypes = {
  invoice: React.PropTypes.object, // 发票详情
  handleShowBrief: React.PropTypes.func, // 收起详情
  canExpense: React.PropTypes.bool, // 发票能否生成费用
  getCurrencyPrecision: React.PropTypes.func, // 币种精度
  getInvoiceFreePrint: React.PropTypes.func, // 能否打印
  handlePrint: React.PropTypes.func // 打印
};
InvoiceDetail.propTypes = {};

export default InvoiceDetail;
